﻿using System;
using System.Web.Mvc;
using Gfw.BLL.Basic.Account;
using Gfw.BLL.Basic.Stock;
using Gfw.BLL.Basic.User;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Web.Common;
using Gfw.Web.Models.Account;
using Gfw.Web.Models.Stock;

namespace Gfw.Web.Controllers
{
    [LAuthorize]
    public class UserAccountController : Controller
    {
        #region Const & Session

        private const string USERACCOUNTCONTROLLER_WARRANTQUERYMODEL = "WarrantQueryModel";
        private const string USERACCOUNTCONTROLLER_WARRANTPAGEINDEX = "WarrantPageIndex";


        private int WarrantPageIndex
        {
            get { return Session[USERACCOUNTCONTROLLER_WARRANTPAGEINDEX].ConvertTo<int>(1); }
            set { Session[USERACCOUNTCONTROLLER_WARRANTPAGEINDEX] = value; }
        }

        private WarrantTransferQueryViewModel WarrantQueryModel
        {
            get { return Session[USERACCOUNTCONTROLLER_WARRANTQUERYMODEL].ConvertTo<WarrantTransferQueryViewModel>(null); }
            set { Session[USERACCOUNTCONTROLLER_WARRANTQUERYMODEL] = value; }
        }

        #endregion

        #region 用户账户基本信息

        /// <summary>
        /// Get，PartialView
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexPartial()
        {
            var model = UserAccountLogic.GetUserAccountSummary(L.Manage.Authentication.Context.CurrentUser.Id);
            return PartialView(model);
        }

        #endregion

        #region 现金币转电子币

        /// <summary>
        /// 用户内部货币转换，现金币转换到电子币
        /// </summary>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpGet]
        public ActionResult ToECurrency()
        {
            var account = UserAccountLogic.GetUserAccount(L.Manage.Authentication.Context.CurrentUser.Id);

            ToECurrencyModel model = new ToECurrencyModel()
                                         {
                                             Cash = account.Cash,
                                             ElectronicMoney = account.ElectronicMoney,
                                         };

            return View(model);
        }

        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpPost]
        public ActionResult ToECurrency(ToECurrencyModel model)
        {
            try
            {
                UserAccountLogic.ToECurrency(L.Manage.Authentication.Context.CurrentUser.Id, model.Count);
                return RedirectToAction("ToECurrency");
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
                return View(model);
            }
        }

        #endregion

        #region 电子币转股票币

        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpGet]
        public ActionResult ToSCurrency()
        {
            var account = UserAccountLogic.GetUserAccount(L.Manage.Authentication.Context.CurrentUser.Id);
            var stock = UsAccountLogic.GetUserAccount(L.Manage.Authentication.Context.CurrentUser.Id);

            ToSCurrencyModel model = new ToSCurrencyModel()
            {
                SMoney = stock.StockMoney,
                EMoney = account.ElectronicMoney,
            };
            return View(model);
        }

        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpPost]
        public ActionResult ToSCurrency(ToSCurrencyModel model)
        {
            try
            {
                UsAccountLogic.ToSCurrency(L.Manage.Authentication.Context.CurrentUser.Id, model.Count);
                return RedirectToAction("ToSCurrency");
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
                return View(model);
            }
        }

        #endregion

        #region 用户转账

        /// <summary>
        /// 普通转账
        /// </summary>
        /// <param name="d">该页面是否转账完成，如果是，则需要显示提示框</param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpGet]
        public ActionResult Transfer(bool? d)
        {

            ViewBag.Done = d.HasValue ? d.Value : false;
            var account = UserAccountLogic.GetUserAccount(L.Manage.Authentication.Context.CurrentUser.Id);
            TransferModel model = new TransferModel()
                                      {
                                          Balance = account != null ? account.ElectronicMoney : 0,
                                          Count = 0,
                                          ToUser = ""
                                      };
            return View(model);
        }

        /// <summary>
        /// 普通转账
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpPost]
        public ActionResult Transfer(TransferModel model)
        {
            ViewBag.Done = false;
            try
            {
                if (L.Manage.Authentication.Context.CurrentUser.LoginName == model.ToUser)
                    throw new GfwVerifyException("转入用户不能是当前用户！");
                UserAccountLogic.Transfer(L.Manage.Authentication.Context.CurrentUser.Id, model);
                return RedirectToAction("Transfer", new { d = true });
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
                return View(model);
            }
        }

        /// <summary>
        /// 普通转账 查询
        /// </summary>
        /// <param name="model"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult TransferQuery(TransferQueryViewModel model, int? page)
        {
            if (model == null)
                model = new TransferQueryViewModel()
                            {
                                Start = null,
                                End = null,
                            };
            if (page == null || page.Value <= 0)
                page = 1;

            int totalSize = 1;
            model.Results = UserAccountLogic.TransferQuery(L.Manage.Authentication.Context.CurrentUser.Id, model.Start, model.End,
                                             page.Value, ViewHelper.PageSize, out totalSize);
            return View(model);
        }


        /// <summary>
        /// 担保转账（会员电子币之间交易）
        /// </summary>
        /// <param name="d">该页面是否转账完成，如果是，则需要显示提示框</param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult WarrantTransfer(bool? d)
        {
            ViewBag.Done = d.HasValue ? d.Value : false;

            var user = UserLogic.GerUserInfo(L.Manage.Authentication.Context.CurrentUser.Id);
            var account = UserAccountLogic.GetUserAccount(L.Manage.Authentication.Context.CurrentUser.Id);
            var finance = UserLogic.GetUserFinanceByUserID(L.Manage.Authentication.Context.CurrentUser.Id);

            WarrantTransferModel model = new WarrantTransferModel()
            {
                UserID = L.Manage.Authentication.Context.CurrentUser.Id,
                QQ = user != null ? user.Qq : string.Empty,
                Tel = user != null ? user.Tel : string.Empty,
                Balance = account != null ? account.ElectronicMoney : 0,
                Count = 0,
                ToUser = "",

                BankAddress = finance != null ? finance.BankAddress : string.Empty,
                BankCardNo = finance != null ? finance.BankCardNo : string.Empty,
                BankName = finance != null ? finance.BankName : string.Empty,
                BankUserName = finance != null ? finance.BankUserName : string.Empty,
                Alipay = finance != null ? finance.Alipay : string.Empty,
                TenPay = finance != null ? finance.TenPay : string.Empty,
            };

            return View(model);
        }

        /// <summary>
        /// 担保转账（会员电子币之间交易）
        /// </summary>
        /// <param name="model"></param>
        /// <param name="transferInfo">转账方式（银行，支付宝，财付通）</param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpPost]
        public ActionResult WarrantTransfer(WarrantTransferModel model, string transferInfo)
        {
            ViewBag.Done = false;

            try
            {
                if (L.Manage.Authentication.Context.CurrentUser.LoginName == model.ToUser)
                    throw new GfwVerifyException("转入用户不能是当前用户！");

                string bankName = string.Empty, bankCardNo = string.Empty, bankUserName = model.BankUserName;

                switch (transferInfo)
                {
                    case "Bank":
                        bankName = model.BankName;
                        bankCardNo = model.BankCardNo;
                        break;
                    case "Tenpay":
                        bankName = "财付通";
                        bankCardNo = model.TenPay;
                        break;
                    case "Alipay":
                        bankName = "支付宝";
                        bankCardNo = model.Alipay;
                        break;

                    default:
                        throw new GfwVerifyException("请选择交易方式");
                }

                UserAccountLogic.WarrantTransfer(model, bankName, bankCardNo, bankUserName);
                return RedirectToAction("WarrantTransfer", new { d = true });
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }


        /// <summary>
        /// 查询担保交易
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult WarrantTransferQueryIndex(WarrantTransferQueryViewModel model)
        {
            WarrantQueryModel = model;
            WarrantPageIndex = 1;

            UserWarrantStatusListModel warrantStatusList = new UserWarrantStatusListModel();
            ViewBag.WarrantStatusList = new SelectList(warrantStatusList.GetUserWarrantStatusList(), "Value", "Key");

            return View(model);
        }

        /// <summary>
        /// 返回指定页面
        /// </summary>
        /// <param name="page">从第一页开始计算</param>
        /// <returns></returns>
        public ActionResult WarrantTransferQueryList(int? page)
        {
            int totalSize, index = page ?? WarrantPageIndex;
            if (index < 1)
                index = 1;

            string userID = L.Manage.Authentication.Context.CurrentUser.Id;

            if (WarrantQueryModel != null)
            {
                var list = UserAccountLogic.WarrantTransferQuery(userID, WarrantQueryModel.Status,
                    WarrantQueryModel.Start, WarrantQueryModel.End, index - 1, ViewHelper.PageSize, out totalSize);
                ViewBag.TotalSize = totalSize;
                WarrantPageIndex = ViewBag.PageIndex = index;

                return PartialView(list);
            }
            else
                return PartialView(null);
        }


        /// <summary>
        /// 查询担保详情
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="toUserID"></param>
        /// <param name="tradeDate"></param>
        /// <param name="status">显示所选状态</param>
        /// <param name="current">当前用户ID</param>
        /// <returns></returns>
        public ActionResult WarrantTransferDetail(string userID,
            string toUserID, DateTime tradeDate, string status, string current)
        {
            var model = UserAccountLogic.GetWarrantByBothUserIDAndTradeDate(userID, toUserID, tradeDate, status, current);

            if (model == null)
                return HttpNotFound();

            return View(model);
        }

        /// <summary>
        /// 买家已转账
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="toUserID"></param>
        /// <param name="tradeDate"></param>
        /// <param name="status">显示所选状态</param>
        /// <param name="current">当前用户ID</param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult WarrantTransferHasTransfer(string userID,
            string toUserID, DateTime tradeDate, string status, string current)
        {
            var model = UserAccountLogic.GetWarrantByBothUserIDAndTradeDate(userID, toUserID, tradeDate, status, current);

            if (model == null)
                return HttpNotFound();

            return View(model);
        }

        /// <summary>
        /// 买家已转账
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpPost]
        public ActionResult WarrantTransferHasTransfer(WarrantDetailModel model)
        {
            try
            {
                UserAccountLogic.WarrantTransferHasTransfer(model);
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return RedirectToAction("WarrantTransferQueryIndex");
        }

        /// <summary>
        /// 买家已撤销
        /// </summary>
        /// <param name="toSellerID">卖家ID</param>
        /// <param name="tradeDate"></param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult WarrantTransferReturn(string toSellerID, DateTime tradeDate)
        {
            string buyID = L.Manage.Authentication.Context.CurrentUser.Id; // 买家ID
            string buyerLoginName = L.Manage.Authentication.Context.CurrentUser.LoginName; // 买家登录名

            UserAccountLogic.WarrantTransferReturn(buyID, buyerLoginName, toSellerID, tradeDate);
            return RedirectToAction("WarrantTransferQueryList");
        }

        /// <summary>
        /// 卖家已确认
        /// </summary>
        /// <param name="toUserID"></param>
        /// <param name="tradeDate"></param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult WarrantTransferAck(string toUserID, DateTime tradeDate)
        {
            string userID = L.Manage.Authentication.Context.CurrentUser.Id;
            string userLoginName = L.Manage.Authentication.Context.CurrentUser.LoginName;

            UserAccountLogic.WarrantTransferAck(userID, userLoginName, toUserID, tradeDate);
            return RedirectToAction("WarrantTransferQueryList");
        }

        #endregion

        #region 用户充值查询

        /// <summary>
        /// 充值查询
        /// </summary>
        /// <param name="model"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult RechargeQuery(RechargeQueryViewModel model, int? page)
        {
            if (model == null)
                model = new RechargeQueryViewModel()
                {
                    Start = null,
                    End = null,
                };

            if (page == null || page.Value <= 0)
                page = 1;

            int totalSize = 1;
            model.Results = UserAccountLogic.RechargeQuery(L.Manage.Authentication.Context.CurrentUser.Id, model.Start, model.End,
                                             page.Value, ViewHelper.PageSize, out totalSize);

            return View(model);
        }

        #endregion

        #region 用户提现

        /// <summary>
        /// 提现申请（预提）
        /// </summary>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult CashApply()
        {
            var account = UserAccountLogic.GetUserAccount(L.Manage.Authentication.Context.CurrentUser.Id);
            var finance = UserLogic.GetUserFinanceByUserID(L.Manage.Authentication.Context.CurrentUser.Id);

            CashModel model = new CashModel()
            {
                Balance = account.Cash,
                Count = 100, // 至少100元起，且为100的整数倍

                BankAddress = finance != null ? finance.BankAddress : string.Empty,
                BankCardNo = finance != null ? finance.BankCardNo : string.Empty,
                BankName = finance != null ? finance.BankName : string.Empty,
                BankUserName = finance != null ? finance.BankUserName : string.Empty,
                Alipay = finance != null ? finance.Alipay : string.Empty,
                TenPay = finance != null ? finance.TenPay : string.Empty,

                UserID = L.Manage.Authentication.Context.CurrentUser.Id,
            };

            return View(model);
        }

        /// <summary>
        /// 提现申请（预提，先扣用户账户，等待审核）
        /// </summary>
        /// <param name="model"></param>
        /// <param name="transferInfo">转账方式（银行，支付宝，财付通）</param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [HttpPost]
        public ActionResult CashApply(CashModel model, string transferInfo)
        {
            try
            {
                if (!(model.Balance >= 100 && DateTime.Today.DayOfWeek != DayOfWeek.Saturday &&
                    DateTime.Today.DayOfWeek != DayOfWeek.Sunday && DateTime.Now.Hour >= 8 &&
                    DateTime.Now.Hour <= 16))
                {
                    throw new GfwVerifyException("请在TX申请时间范围内操作！");
                }

                long count; // 提现金额，至少100元起，且为100的整数倍
                if (!long.TryParse(model.Count.ToString(), out count))
                {
                    throw new GfwVerifyException("输入的金额不正确！");
                }
                else if (count > model.Balance || count <= 0)
                {
                    throw new GfwVerifyException("金额不正确！");
                }
                else if (count % 100 != 0) // 判断100的倍数
                {
                    throw new GfwVerifyException("金额为100的整数倍！");
                }


                string bankName = string.Empty, bankCardNo = string.Empty, bankUserName = model.BankUserName;

                switch (transferInfo)
                {
                    case "Bank":
                        bankName = model.BankName;
                        bankCardNo = model.BankCardNo;
                        break;
                    case "Tenpay":
                        bankName = "财付通";
                        bankCardNo = model.TenPay;
                        break;
                    case "Alipay":
                        bankName = "支付宝";
                        bankCardNo = model.Alipay;
                        break;

                    default:
                        throw new GfwVerifyException("请选择TX方式");
                }

                UserAccountLogic.CashApply(L.Manage.Authentication.Context.CurrentUser.Id, count,
                    bankName, bankCardNo, bankUserName);

                return RedirectToAction("CashResult");
            }
            catch (System.Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
                return View(model);
            }
        }

        /// <summary>
        /// 会员提现明细查询（前台）
        /// </summary>
        /// <param name="model"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult CashQuery(CashQueryViewModel model, int? page)
        {
            if (model == null)
                model = new CashQueryViewModel()
                {
                    Start = null,
                    End = null,
                };

            if (page == null || page.Value <= 0)
                page = 1;

            int totalSize = 1;
            model.Results = UserAccountLogic.CashQuery(L.Manage.Authentication.Context.CurrentUser.Id, model.Start, model.End,
                                             page.Value, ViewHelper.PageSize, out totalSize);
            return View(model);
        }


        //BMK Result界面
        /// <summary>
        /// 申请成功后，返回页面
        /// </summary>
        /// <returns></returns>
        public ActionResult CashResult()
        {
            return View();
        }

        #endregion

        #region 动态奖金查询

        /// <summary>
        /// 当前选择的页数
        /// </summary>
        /// 如果是选择参数，也可以这样处理
        int PageIndex
        {
            get { return Session["AwardQuery_PageIndex"].ConvertTo<int>(1); }
            set { Session["AwardQuery_PageIndex"] = value; }
        }

        private AwardQueryModel QueryModel
        {
            get { return Session["AwardQuery_AwardQueryModel"].ConvertTo<AwardQueryModel>(null); }
            set { Session["AwardQuery_AwardQueryModel"] = value; }
        }

        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult AwardQuery(AwardQueryModel model)
        {

            QueryModel = model;
            PageIndex = 1;
            return View(model);
        }

        public PartialViewResult AwardQueryList(int? page)
        {

            int totalSize;
            int index = page ?? PageIndex;
            if (index < 1) index = 1;

            var list = UserAccountLogic.AwardQuery(L.Manage.Authentication.Context.CurrentUser.Id, QueryModel.AwardType, QueryModel.Start, QueryModel.End, index - 1, ViewHelper.PageSize, out totalSize);
            ViewBag.TotalSize = totalSize;
            PageIndex = ViewBag.PageIndex = index;

            return PartialView(list);

        }

        #endregion

        #region 现金币交易查询

        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult BcQuery(Gfw.Web.Models.Account.BargainQueryModel model)
        {

            return View(model);
        }
        public PartialViewResult BcQueryList(DateTime? Start, DateTime? End, int? page)
        {
            int totalSize;
            int index = page ?? PageIndex;
            if (index < 1) index = 1;
            var list = UserAccountLogic.BargainCashQuery(L.Manage.Authentication.Context.CurrentUser.Id, Start, End, index - 1, ViewHelper.PageSize, out totalSize);
            ViewBag.TotalSize = totalSize;
            ViewBag.Model = new { Start = Start, End = End };
            ViewBag.PageIndex = index;
            return PartialView(list);
        }
        #endregion

        #region 电子币交易查询

        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        public ActionResult BeQuery(Gfw.Web.Models.Account.BargainQueryModel model)
        {

            return View(model);
        }

        public PartialViewResult BeQueryList(DateTime? Start, DateTime? End, int? page)
        {
            int totalSize;
            int index = page ?? PageIndex;
            if (index < 1) index = 1;
            var list = UserAccountLogic.BargainEmoneyQuery(L.Manage.Authentication.Context.CurrentUser.Id, Start, End, index - 1, ViewHelper.PageSize, out totalSize);
            ViewBag.TotalSize = totalSize;
            ViewBag.Model = new { Start = Start, End = End };
            ViewBag.PageIndex = index;
            return PartialView(list);
        }

        #endregion
    }
}
